package com.cswnode.demo.service.impl;

import com.cswnode.demo.dao.StudentDao;
import com.cswnode.demo.entity.ClassRoom;
import com.cswnode.demo.entity.Student;
import com.cswnode.demo.entity.User;
import com.cswnode.demo.enums.typeEnum;
import com.cswnode.demo.service.ClassRoomService;
import com.cswnode.demo.service.StudentService;
import com.cswnode.demo.service.UserService;
import com.cswnode.demo.util.Constant;
import com.cswnode.demo.util.Utils;
import com.cswnode.demo.vo.StuQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 学生信息表(Student)表服务实现类
 *
 * @author makejava
 * @since 2021-03-20 15:51:03
 */
@Service("studentService")
public class StudentServiceImpl implements StudentService , Constant {
    @Resource
    private StudentDao studentDao;
    @Autowired
    private UserService userService;
    @Autowired
    private ClassRoomService classRoomService;

    /**
     * 事物
     */
    @Autowired
    private DataSourceTransactionManager transactionManager;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Student queryById(Long id) {
        return this.studentDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */

    @Override
    public List<Student> queryAllByLimit(int offset, int limit, StuQuery stuQuery) {
        return studentDao.queryAllByLimit(offset, limit, stuQuery);
    }

    @Override
    public int selectNum(StuQuery stuQuery) {
        return studentDao.selectNum(stuQuery);
    }



    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public String insert(Student student) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            User user = copyUser(student);
            user.setPassword(user.getUsername());
            Map<String, Object> insert = userService.insert(user);
            if (insert.containsKey(SUCCESS)){
                User success = (User)insert.get(SUCCESS);
                ClassRoom classRoom = classRoomService.queryById(student.getClassId());
                student.setClassName(classRoom.getClassName());
                student.setUserId(success.getUserId());
                student.setCreateTime(user.getCreateTime());
                student.setIsDelete(user.getIsDelete());
                int result = studentDao.insert(student);
                if (result != 1){
                    throw new RuntimeException("添加失败");
                }
                return null;
            }
            return (String) insert.get(ERROR);

        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    private User copyUser(Student student){
        User user = new User();
        user.setUsername(student.getStuId());
        user.setPhone(student.getPhone());
        user.setType(typeEnum.STUDENT.getCode());
        user.setSex(student.getSex());
        user.setUserNameCn(student.getName());
        user.setEmail(student.getEmail());
        if (null != student.getUserId()){
            user.setUserId(student.getUserId());
        }
        return user;
    }

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public String update(Student student) {
        student.setClassName("");
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("UpdateStudent");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            User user = copyUser(student);
            String s = userService.updateUser(user);
            if (s == null){
                ClassRoom classRoom = classRoomService.queryById(student.getClassId());
                student.setClassName(classRoom.getClassName());
                int update = studentDao.update(student);
                if (update != 1){
                    throw new RuntimeException("修改失败");
                }
                return null;
            }
            return s;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @Transactional
    public boolean deleteById(Long id) {
        if (id == null) {
            return false;
        }
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("deleteStu");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            Student student = queryById(id);
            if (null == student || null == student.getUserId()){
                return false;
            }
            userService.deleteById(student.getUserId());
            studentDao.deleteById(id);
            return true;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    @Override
    public Student getStudent() {
        Long userId = Utils.getLoginUser().getUserId();
        Student studentByUserId = studentDao.getStudentByUserId(userId);
        return studentByUserId;
    }
}